import router from './index'
import { useUserStore } from '@/stores'
const allowList = ['/','/login', '/403', '/404'] //直接跳转网页（白名单）

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore() // 确保在路由守卫内调用 store
  // eslint-disable-next-line no-unused-vars
  const { token, getRole, FETCH_PERMISSION, identification } = userStore
  // console.log(555, token)
  // console.log('跳转路由', to.path)

  if (allowList.includes(to.path)) {
    // 在免登录名单，直接进入
    // console.log(to.path,'在免登录名单')
    next()
  } else {
    // console.log('查看权限：', to.matched)
    // 页面是否需要登录
    if (
      to.matched.length > 0 &&
      !to.matched.some((record) => record.meta.requiresAuth)
    ) {
      // console.log('不需要权限')
      next()
    } else {
      if (!token) {
        // console.log('没有token,跳转/403')
        next({
          path: '/403'
        })
      } else {
        // console.log('有token,准备验证identification/ident')
        let res = await identification()
        // console.log(33, res)
        const { code } = res
        if (code == 200) {
          // console.log('先获取动态路由', to)
          // FETCH_PERMISSION() 先判断动态路由是否生成，没有就生成
          let res2 = await FETCH_PERMISSION()
          if (res2) {
            //  // 重定向当前路径，确保新路由生效
            next({ ...to, replace: true })
          } else {
            next()
          }
        } else if (code == 403) {
          next({
            path: '/403'
          })
        } else {
          next({
            path: '/404'
          })
        }
      }
    }
  }

  // next()
})
export default router
